package main.java.com.bookmanager.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import main.java.com.bookmanager.model.Book;
import main.java.com.bookmanager.model.User;
import main.java.com.bookmanager.service.BookService;
import main.java.com.bookmanager.util.Classify;
import main.java.com.bookmanager.util.UserUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/user")
@MultipartConfig
public class UserServlet extends HttpServlet {
    private BookService bookService = new BookService();
    UserUtil userUtil = new UserUtil();
    User thisUser;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
        switch (action) {
            case "register":
                handleRegisterUser(request, response);
                break;
            case "get":
                handleGetBook(request, response);
                break;
            case "getAll":
                handleGetAllBooks(request, response);
                break;
            case "login":
                handleLoginUser(request, response);
                break;
            case "allLend":
                handleMyAllLendBooks(request, response);
                break;
            case "borrow":
                handleBorrowBook(request, response);
                break;
            case "return":
                handleReturnBook(request, response);
                break;
            default:
                out.println("无效操作！");
                break;
        }
    }

    public void handleReturnBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int bookId = Integer.parseInt(request.getParameter("id"));
        Classify classify = Classify.valueOf(request.getParameter("classify"));
        Book book=bookService.getBooks(classify, bookId);
        if (book == null) {
            out.println("无此书籍！");
        }
        if (userUtil.returnBook(book,thisUser)){
            out.println("归还成功！");
            return;
        }
        out.println("归还失败！");
    }

    public void handleMyAllLendBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<style>");
        out.println("  table { border-collapse: collapse; width: 100%; }");
        out.println("  th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }");
        out.println("  th { background-color: #f2f2f2; }");
        out.println("</style>");
        out.println("<h1>书籍列表</h1>");
        out.println("<table>");
        out.println("<tr>");
        out.println("<th>ID</th>");
        out.println("<th>名称</th>");
        out.println("<th>作者</th>");
        out.println("<th>类型</th>");
        out.println("<th>状态</th>");
        out.println("<th>归还期限</th>");
        out.println("</tr>");
        for (Book book : thisUser.getBooks()){
            out.println("<tr>");
            out.println("  <td>" + book.getBookId() + "</td>");
            out.println("  <td>" + book.getBookName() + "</td>");
            out.println("  <td>" + book.getBookAuthor() + "</td>");
            out.println("  <td>" + book.getClassify() + "</td>");
            out.println("  <td>" + book.getStatus() + "</td>");
            out.println("  <td>" + book.getReturnDate() + "</td>");
            out.println("</tr>");
        }
        out.println("</table>");
        out.println("</body></html>");
    }

    public void handleBorrowBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int bookId = Integer.parseInt(request.getParameter("id"));
        Classify classify =  Classify.valueOf(request.getParameter("classify"));
        Book book = bookService.getBooks(classify, bookId);
        if (book == null){
            out.println("无此书籍！");
            return;
        }
        if (userUtil.lendBook(book,thisUser)){
            out.println("借阅成功！");
            return;
        }
        out.println("借阅失败！");
    }

    protected void handleLoginUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        thisUser=userUtil.verification(request.getParameter("email"), request.getParameter("password"));
        if (thisUser == null) {
            response.sendRedirect("/login.jsp?error=invalid");
            out.println("<script>");
            out.println("alert('登录成功！');");
            out.println("window.location.href = 'index.html';");
            out.println("</script>");
            return;
        }
        out.println("<script>");
        out.println("alert('无此用户！请注册！');");
        out.println("window.location.href = 'index.html';");
        out.println("</script>");
        response.sendRedirect("/html/user/user.jsp");
    }

    protected void handleRegisterUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        userUtil.addUser(username, email, password);
        thisUser=userUtil.verification(email, password);
        response.sendRedirect("/html/user/user.jsp");
    }

    protected void handleGetBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Book book = null;
        try {
            Classify classify = Classify.valueOf(request.getParameter("classify"));
            int id = Integer.parseInt(request.getParameter("id"));
            book = bookService.getBooks(classify, id);
        } catch (IllegalArgumentException e) {
            out.println("无法找到相关书籍！");
        }
        out.println("<html><body>");
        out.println("<style>");
        out.println("  table { border-collapse: collapse; width: 100%; }");
        out.println("  th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }");
        out.println("  th { background-color: #f2f2f2; }");
        out.println("</style>");
        out.println("<h1>查询到的书籍</h1>");
        out.println("<table>");
        out.println("<tr>");
        out.println("<th>ID</th>");
        out.println("<th>名称</th>");
        out.println("<th>作者</th>");
        out.println("<th>类型</th>");
        out.println("<th>状态</th>");
        out.println("<th>在馆数量</th>");
        out.println("<th>借出</th>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("  <td>" + book.getBookId() + "</td>");
        out.println("  <td>" + book.getBookName() + "</td>");
        out.println("  <td>" + book.getBookAuthor() + "</td>");
        out.println("  <td>" + book.getClassify() + "</td>");
        out.println("  <td>" + book.getStatus() + "</td>");
        out.println("  <td>" + book.getQuantity() + "</td>");
        out.println("  <td>" + book.getLend() + "</td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("</body></html>");
    }

    protected void handleGetAllBooks(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<style>");
        out.println("  table { border-collapse: collapse; width: 100%; }");
        out.println("  th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }");
        out.println("  th { background-color: #f2f2f2; }");
        out.println("</style>");
        out.println("<h1>书籍列表</h1>");
        out.println("<table>");
        out.println("<tr>");
        out.println("<th>ID</th>");
        out.println("<th>名称</th>");
        out.println("<th>作者</th>");
        out.println("<th>类型</th>");
        out.println("<th>状态</th>");
        out.println("<th>归还期限</th>");
        out.println("</tr>");
        Classify classify = Classify.valueOf(request.getParameter("classify"));
        List<Book> bookList = thisUser.getBooks();
        List<Book> sortedList = bookList.stream()
                .sorted(Comparator.comparingInt(Book::getBookId))
                .collect(Collectors.toList());
        for (Book book : sortedList) {
            out.println("<tr>");
            out.println("  <td>" + book.getBookId() + "</td>");
            out.println("  <td>" + book.getBookName() + "</td>");
            out.println("  <td>" + book.getBookAuthor() + "</td>");
            out.println("  <td>" + book.getClassify() + "</td>");
            out.println("  <td>" + book.getStatus() + "</td>");
            out.println("  <td>" + book.getReturnDate() + "</td>");
            out.println("</tr>");
        }
        out.println("</table>");
        out.println("</body></html>");
    }
}
